package in.waffl.fairycake;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
import java.awt.image.RescaleOp;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

public class Sprite {
	private BufferedImage filmstrip;
	private final int width;
	private final int height;
	private float alpha = 1;
	public Sprite(InputStream imageStream, int width, int height, Color transparent) throws IOException {
		this.width = width;
		this.height = height;
        Image image = makeColorTransparent(ImageIO.read(imageStream), Color.magenta);
        filmstrip = imageToBufferedImage(image);
	}
	public Sprite(InputStream imageStream, int width, int height) throws IOException {
		this.width = width;
		this.height = height;
        filmstrip = imageToBufferedImage(ImageIO.read(imageStream));
	}
	public void draw(Graphics2D g, Canvas c, int x, int y, int imageIndex) {
		BufferedImage frame = filmstrip.getSubimage((getWidth()+1)*imageIndex+1, 1, getWidth(), getHeight()+1);
		if (alpha != 1) {
			float[] scales = { 1f, 1f, 1f, alpha};
			float[] offsets = new float[4];
			RescaleOp rop = new RescaleOp(scales, offsets, null);
			g.drawImage(frame, rop, x, y);
		} else {
			g.drawImage(frame, x, y, c);
		}
	}
	private static BufferedImage imageToBufferedImage(Image image) {
		BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
		Graphics2D g2 = bufferedImage.createGraphics();
		g2.drawImage(image, 0, 0, null);
		g2.dispose();

		return bufferedImage;
	}
	public static Image makeColorTransparent(BufferedImage im, final Color color) {
		ImageFilter filter = new RGBImageFilter() {
			//extract rgb from color, remove all alpha
			public int markerRGB = color.getRGB() | 0xFF000000;
			public final int filterRGB(int x, int y, int rgb) {
				if ((rgb | 0xFF000000) == markerRGB) return 0x00FFFFFF & rgb;
				return rgb;
			}
		};
		ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
		return Toolkit.getDefaultToolkit().createImage(ip);
	}
	public int getWidth() {
		return width;
	}
	public int getHeight() {
		return height;
	}
	public float getAlpha() {
		return alpha;
	}
	public void setAlpha(float alpha) {
		this.alpha = alpha;
	}
}
